package mysql

import (
	"e_mall_server/models"
	"go.uber.org/zap"
)

/**
 * @Author: zhaobin
 * @Description TODO
 * @Date: 2022-05-10 15:47
 */

// GetGoodsList 获取商品列表接口
func GetGoodsList(pageParam *models.PageParam) ([]models.Goods, error) {
	var goodsList []models.Goods
	num := pageParam.PageNum
	size := pageParam.PageSize
	err := db.Preload("GoodsAttrList").Where("title LIKE ?", pageParam.Query).Offset((num - 1) * size).Limit(size).Find(&goodsList).Error
	if err != nil {
		return nil, err
	}
	return goodsList, nil
}

// GetGoodsByMap 通过分类获取商品列表接口
func GetGoodsByMap(query map[string]interface{}, goodsQueryParam *models.GoodsQueryParam) ([]models.Goods, error) {
	var goodsList []models.Goods
	num := goodsQueryParam.PageNum
	size := goodsQueryParam.PageSize
	//zap.L().Debug("查询条件", zap.Any("value", query))
	err := db.Debug().Where(query).Where("title LIKE ?", goodsQueryParam.Query).Offset((num - 1) * size).Limit(size).Find(&goodsList).Error
	if err != nil {
		return nil, err
	}
	return goodsList, nil
}

func GetGoodsCountByMap(query map[string]interface{}, goodsQueryParam *models.GoodsQueryParam) int64 {
	var count int64
	db.Model(&models.Goods{}).Where(query).Where("title LIKE ?", goodsQueryParam.Query).Count(&count)
	return count
}

func GetGoodsCount(pageParam *models.PageParam) int64 {
	var count int64
	db.Model(&models.Goods{}).Where("title LIKE ?", pageParam.Query).Count(&count)
	return count
}

// AddGoods 添加商品信息
func AddGoods(Goods *models.Goods) error {
	zap.L().Debug("mysql.AddGoods()", zap.Any("商品信息", Goods))
	// 进行数据库添加操作
	return db.Create(Goods).Error
}

// UpdateGoods 修改商品信息
func UpdateGoods(Goods *models.Goods) int64 {
	// 进行数据库修改操作
	value := db.Debug().Model(&Goods).Updates(&Goods)
	return value.RowsAffected
}

// DeleteGoodsById 通过商品id删除商品数据
func DeleteGoodsById(id int64) int64 {
	return db.Delete(&models.Goods{Id: id}).RowsAffected
}

// GetGoodsById 通过id查看商品信息
func GetGoodsById(id int64) models.Goods {
	Goods := models.Goods{Id: id}
	db.Find(&Goods)
	return Goods
}

// GetGoodsDetailById 通过商品id获取商品详细信息
func GetGoodsDetailById(id int64) (goods models.Goods, err error) {
	goods.Id = id
	err = db.Where("id = ?", id).Find(&goods).Error
	return
}
